package com.xxc.domain.strategy.service.armory;

import com.xxc.domain.strategy.model.entity.StrategyAwardEntity;
import com.xxc.domain.strategy.model.entity.StrategyEntity;
import com.xxc.domain.strategy.model.entity.StrategyRuleEntity;
import com.xxc.domain.strategy.repository.IStrategyRepository;
import com.xxc.types.common.Constants;
import com.xxc.types.enums.ResponseCode;
import com.xxc.types.exception.AppException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.security.SecureRandom;
import java.util.*;

/**
 * @Author: xxc
 * @Description: 策略装配库（兵工厂），负责初始化策略计算
 * @Date: 2025/1/19 19:28
 * @Version: 1.0
 */

@Slf4j
@Service
public class StrategyArmoryDispatch implements IStrategyArmory, IStrategyDispatch {

    @Resource
    private IStrategyRepository repository;

    /**
     * 装配抽奖策略
     *
     * @param strategyId
     * @return
     */
    @Override
    public boolean assembleLotteryStrategy(Long strategyId) {
        // 1. 【查询策略奖品配置】（获得StrategyAwardEntity中的字段，包含奖品的信息、概率等信息）
        List<StrategyAwardEntity> strategyAwardEntities = repository.queryStrategyAwardList(strategyId);
        if (strategyAwardEntities.isEmpty()) {
            return false;
        }

        // 2. 缓存奖品库存【用于decr扣减库存使用】
        for (StrategyAwardEntity strategyAward : strategyAwardEntities) {
            Integer awardId = strategyAward.getAwardId();
            Integer awardCount = strategyAward.getAwardCount();
            cacheStrategyAwardCount(strategyId, awardId, awardCount);
        }

        // 3.1 默认策略配置【全量抽奖概率】
        assembleLotteryStrategy(String.valueOf(strategyId), strategyAwardEntities);

        // 3.2. 【权重策略配置】 适用于rule_weight权重规则配置
        // 3.2.1 查询strategy表的rule_model，有没有rule_weight这个规则，没有直接返回
        StrategyEntity strategyEntity = repository.queryStrategyEntityByStrategyId(strategyId);
        String ruleWeight = strategyEntity.getRuleWeight();
        if (null == ruleWeight) return true;

        // 3.2.2 查strategy_rule表获取详细rule_weight配置
        StrategyRuleEntity strategyRuleEntity = repository.queryStrategyRule(strategyId, ruleWeight);
        // 没查到rule_weight，做异常处理（strategy表里面有但是strategy_rule表里没有肯定是有问题）
        if (null == strategyRuleEntity) {
            throw new AppException(ResponseCode.STRATEGY_RULE_WEIGHT_IS_NULL.getCode(),
                    ResponseCode.STRATEGY_RULE_WEIGHT_IS_NULL.getInfo());
        }
        // 查到rule_weight，解析rule_value
        Map<String, List<Integer>> ruleWeightValueMap = strategyRuleEntity.getRuleWeightValues();
        Set<String> keys = ruleWeightValueMap.keySet();
        for (String key : keys) {
            List<Integer> ruleWeightValues = ruleWeightValueMap.get(key);
            // 做一个浅拷贝，清除不在ruleWeightValues里面的元素
            List<StrategyAwardEntity> strategyAwardEntitiesClone = new ArrayList<>(strategyAwardEntities);
            strategyAwardEntitiesClone.removeIf(entity -> !ruleWeightValues.contains(entity.getAwardId()));

            assembleLotteryStrategy(String.valueOf(strategyId).concat(Constants.UNDERLINE).concat(key), strategyAwardEntitiesClone);
        }

        return true;
    }

    private void cacheStrategyAwardCount(Long strategyId, Integer awardId, Integer awardCount) {
        String cacheKey = Constants.RedisKey.STRATEGY_AWARD_COUNT_KEY + strategyId + Constants.UNDERLINE + awardId;
        repository.cacheStrategyAwardCount(cacheKey, awardCount);
    }


    private void assembleLotteryStrategy(String key, List<StrategyAwardEntity> strategyAwardEntities) {
        // 1. 获取最小概率值
        BigDecimal minAwardRate = strategyAwardEntities.stream()
                .map(StrategyAwardEntity::getAwardRate)
                .min(BigDecimal::compareTo)
                .orElse(BigDecimal.ZERO);

        // 2. 获取概率值总和
        BigDecimal totalAwardRate = strategyAwardEntities.stream()
                .map(StrategyAwardEntity::getAwardRate)
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        // 3. 用 1 % 0.0001 获得概率范围，百分位、千分位、万分位  【这里就相当于minAwardRate是最小那份，现在求总共多少份，要分多少个空间】
        BigDecimal rateRange = totalAwardRate.divide(minAwardRate, 0, RoundingMode.CEILING);

        // 4. 生成策略奖品概率查找表  「这里指需要在list集合中，存放上对应的奖品占位即可，占位越多等于概率越高」
        ArrayList<Integer> strategyAwardRateSearchTable = new ArrayList<>(rateRange.intValue());
        for (StrategyAwardEntity strategyAward : strategyAwardEntities) {
            Integer awardId = strategyAward.getAwardId();
            BigDecimal awardRate = strategyAward.getAwardRate();

            // 计算出每个概率值需要存放到查找表的数量
            // int num = rateRange.multiply(awardRate).setScale(0,RoundingMode.CEILING).intValue(); //没考虑概率总和不为1
            int num = awardRate.divide(minAwardRate, 0, RoundingMode.CEILING).intValue();
            // 循环填充
            for (int i = 0; i < num; i++) {
                strategyAwardRateSearchTable.add(awardId);
            }
        }

        // 5. 对存储的奖品进行乱序操作
        Collections.shuffle(strategyAwardRateSearchTable);

        // 6. 生成出Map集合，key值，对应的就是后续随机出来的一个值。通过概率（随机模拟的）来获得对应的奖品ID
        Map<Integer, Integer> shuffledStrategyAwardRateSearchTable = new LinkedHashMap<>();
        for (int i = 0; i < strategyAwardRateSearchTable.size(); i++) {
            shuffledStrategyAwardRateSearchTable.put(i, strategyAwardRateSearchTable.get(i));
        }

        // 7. 存放到 Redis 这里保险起见不能传rateRange，因为有些概率可能不是最小概率的整数倍，向上取整最终格子可能多几个
//        repository.storeStrategyAwardSearchRateTable(strategyId, rateRange, shuffledStrategyAwardRateSearchTable);
        repository.storeStrategyAwardSearchRateTable(key, shuffledStrategyAwardRateSearchTable.size(), shuffledStrategyAwardRateSearchTable);
    }


    /**
     * 抽奖
     *
     * @param strategyId
     * @return
     */
    @Override
    public Integer getRandomAwardId(Long strategyId) {
        // 分布式部署下，不一定为当前应用做的策略装配。也就是值不一定会保存到本应用，而是分布式应用，所以需要从 Redis 中获取。
        // 也就是说，在分布式场景下，抽奖和装配这种大概率是分离的操作，在抽奖时需要从公共Redis重新获取rateRange
        int rateRange = repository.getRateRange(strategyId);

        // 通过生成的随机值，获取概率值奖品查找表的结果
        return repository.getAssembledStrategyAwardId(String.valueOf(strategyId), new SecureRandom().nextInt((rateRange)));
    }

    @Override
    public Integer getRandomAwardId(Long strategyId, String ruleWeightValue) {
        String key = String.valueOf(strategyId).concat("_").concat(ruleWeightValue);

        // 分布式部署下，不一定为当前应用做的策略装配。也就是值不一定会保存到本应用，而是分布式应用，所以需要从 Redis 中获取。
        // 也就是说，在分布式场景下，抽奖和装配这种大概率是分离的操作，在抽奖时需要从公共Redis重新获取rateRange
        int rateRange = repository.getRateRange(key);

        // 通过生成的随机值，获取概率值奖品查找表的结果
        return repository.getAssembledStrategyAwardId(key, new SecureRandom().nextInt((rateRange)));
    }

    @Override
    public Boolean subtractionAwardStock(Long strategyId, Integer awardId) {
        String cacheKey = Constants.RedisKey.STRATEGY_AWARD_COUNT_KEY + strategyId + Constants.UNDERLINE + awardId;
        return repository.subtractionAwardStock(cacheKey);
    }

}
